package servidor.database;
import java.sql.*;
import java.util.ArrayList;
import java.util.Iterator;

public class Conexao {
	private String status = "Connection oppened";
	private Connection conexao = null;
	
	public Conexao(String host, String user, String password, String database){
		try{
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			
			String url = "jdbc:mysql://"+host+"/"+database+"?user="+user+"&password="+password+"";
			conexao = DriverManager.getConnection(url);
		}catch (Exception e) {
			status = e.getMessage();
		}
	}

	public void close() {
		try {
			if (conexao != null) 
				conexao.close();
		} catch (Exception e) {
			status = e.getMessage();
	    }
	}
	
	public ResultSet SelectQuery(String query, ArrayList<String> input){
		ResultSet resultSet = null;
		PreparedStatement preparedStatement = null;
		
		try {
			preparedStatement = conexao.prepareStatement(query);
			
			if(input != null){
				Iterator<String> iterador = input.iterator();
				
				Integer inputNumber = 1;
				while(iterador.hasNext()){
					String argumento = (String)iterador.next();
					preparedStatement.setString(inputNumber, argumento);
					inputNumber++;
				}
				
			}
			
			resultSet = preparedStatement.executeQuery();
		} catch (Exception e){
			status = e.getMessage();
		}
		
		return resultSet;
	}
	
	public Integer UpdateQuery(String query, ArrayList<String> input){
		Integer result = null;
		PreparedStatement preparedStatement = null;
		
		try {
			preparedStatement = conexao.prepareStatement(query);
			
			if(input != null){
				Iterator<String> iterador = input.iterator();
				
				Integer inputNumber = 1;
				while(iterador.hasNext()){
					String argumento = (String)iterador.next();
					preparedStatement.setString(inputNumber, argumento);
					inputNumber++;
				}
				
			}

			result = preparedStatement.executeUpdate();
		} catch (Exception e){
			status = e.getMessage();
		}
		
		return result;
	}
	
	public Connection getConexao(){
		return conexao;
	}

	public String getStatus(){
		return status;
	}
}
